package com.cjdes.recipes4u;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;

import com.cjdes.android.AsyncTaskResult;
import com.cjdes.recipes4u.dto.RecipeStore;
import com.cjdes.recipes4u.jaxb.RecipeUnpacker;

public class MainActivity extends Activity {
	private HashMap<String, String> knownTwitterClients;
	private HashMap<String, ActivityInfo> foundTwitterClients;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		loadStore();
	}
	
	private void loadStore(){
		try {
			final RecipeStore store;
			setContentView(R.layout.activity_main);
			TableLayout layout = (TableLayout) findViewById(R.id.MenuBar);
			AsyncTaskResult<RecipeStore> result = RecipeUnpacker.getRecipeStore();
			if (result == null){
				alertError();
			} else {
			
				store = result.get_result();
				if (store != null){
					addButtons(store, layout);
				} else {
					alertError();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	private void alertError() {
		AlertDialog.Builder alert = new Builder(MainActivity.this);
		alert.setTitle("Could Not Load Recipes");
		alert.setMessage("A data connection is required to load recipes, are you connected?");
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
		});
		AlertDialog dialog = alert.create();
		dialog.show();
		
	}



	private void addButtons(final RecipeStore store, TableLayout layout) {
		int i = 0;
		for (final String type : store.getDistinctRecipeTypes()) {
			
			
			
			final Button button = new Button(this);
			button.setText(type);
			button.setId(i);
			button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(MainActivity.this, ListOfRecipes.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("recipeType", type);
					bundle.putSerializable("recipeStore", store);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			layout.addView(button);
			i++;
		}
		
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		getMenuInflater().inflate(R.menu.header, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
		case R.id.action_refresh:
			loadStore();
			return true;
		default: 
			return super.onOptionsItemSelected(item);
		}
		
	}

	public void onTweetClick(MenuItem mi) {
		detectTwitterClients();
		ComponentName targetComponent = getTwitterClientComponentName();
		String title = "Delicious Home Made Recipe App has great recipes. I'm gonna cook! @jaybow87 http://goo.gl/vbD9rY";
		String permalink = "";
		if (targetComponent != null) {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setComponent(targetComponent);
			String intentType = (targetComponent.getClassName()
					.contains("com.twidroid"))
					? "application/twitter"
					: "text/plain";
			intent.setType(intentType);
			intent.putExtra(Intent.EXTRA_TEXT, title + "\n" + permalink);
			this.startActivity(intent);
		} else {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_TEXT, title + "n" + permalink);
			this.startActivity(Intent.createChooser(intent, "Share..."));
		}
	}

	private void buildKnownTwitterClientsList() {
		knownTwitterClients = new HashMap<String, String>();

		knownTwitterClients.put("Twitter", "com.twitter.android.PostActivity");
		knownTwitterClients
				.put("UberSocial", "com.twidroid.activity.SendTweet");
		knownTwitterClients.put("TweetDeck",
				"com.tweetdeck.compose.ComposeActivity");
		knownTwitterClients.put("Seesmic", "com.seesmic.ui.Composer");
		knownTwitterClients.put("TweetCaster",
				"com.handmark.tweetcaster.ShareSelectorActivity");
		knownTwitterClients.put("Plume",
				"com.levelup.touiteur.appwidgets.TouiteurWidgetNewTweet");
		knownTwitterClients.put("Twicca", "jp.r246.twicca.statuses.Send");
	}

	public boolean detectTwitterClients() {
		buildKnownTwitterClientsList();
		foundTwitterClients = new HashMap<String, ActivityInfo>();

		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activityList = pm.queryIntentActivities(intent, 0);
		int len = activityList.size();
		for (int i = 0; i < len; i++) {
			ResolveInfo app = (ResolveInfo) activityList.get(i);
			ActivityInfo activity = app.activityInfo;
			if (knownTwitterClients.containsValue(activity.name)) {
				foundTwitterClients.put(activity.name, activity);
			}
		}
		return false;
	}

	public ComponentName getTwitterClientComponentName() {
		ComponentName result = null;
		String preferredTwitterClient = null;

		if (foundTwitterClients.size() > 0) {
			ActivityInfo tweetActivity = null;
			for (Map.Entry<String, ActivityInfo> entry : foundTwitterClients
					.entrySet()) {
				tweetActivity = entry.getValue();
				break;
			}
			if (tweetActivity != null) {
				preferredTwitterClient = tweetActivity.name;
			}
			if (preferredTwitterClient != null) {
				String activityName = knownTwitterClients
						.get(preferredTwitterClient);
				if (foundTwitterClients.containsKey(activityName)) {
					tweetActivity = foundTwitterClients.get(activityName);
				}
			}

			result = new ComponentName(
					tweetActivity.applicationInfo.packageName,
					tweetActivity.name);
		}

		return result;
	}

	public boolean connectivityCheck(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;

	}
	
	public static void reloadStore(){
		MainActivity activity = new MainActivity();
		activity.loadStore();
	}
}
